package com.ljf.framework.schedule;

import com.ljf.framework.exception.LjfException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 说明：
 *
 * @Auther: lijinfeng
 * @Date: 2025/1/9
 */
public abstract class LjfScheduleTask {

    // 任务id 自增
    private static final AtomicInteger taskIdGenerator = new AtomicInteger(0);
    private int taskId;
    public String getTaskId() {
        return this.getClass().getSimpleName() + taskId;
    }

    // 任务状态
    private volatile LjfTaskEnum ljfTaskEnum;
    public void setLjfTaskEnum(LjfTaskEnum ljfTaskEnum) {
        this.ljfTaskEnum = ljfTaskEnum;
    }
    public LjfTaskEnum getLjfTaskEnum() {
        return ljfTaskEnum;
    }

    public LjfScheduleTask() {
        this.taskId = taskIdGenerator.incrementAndGet();
        this.ljfTaskEnum = LjfTaskEnum.init;
    }

    /**
     * execute handler, invoked when executor receives a scheduling request
     */
    public abstract void execute() throws Exception;


    /**
     * init handler, invoked when JobThread init
     */
    public abstract void init() throws Exception;


    /**
     * destroy handler, invoked when JobThread destroy
     */
    public abstract void destroy() throws Exception;

    public void run() throws Exception {
        // init
        try {
            init();
        } catch (Throwable e) {
            throw new LjfException(this.taskId+ " init error:" +e.getMessage());
        }
        // execute
        while(ljfTaskEnum == LjfTaskEnum.init) {
            try {
                this.ljfTaskEnum = LjfTaskEnum.running;
                execute();
            } catch (Throwable e) {
                throw new LjfException(this.taskId+ " execute error:" +e.getMessage());
            }
        }
        // destroy
        try {
            destroy();
            this.ljfTaskEnum = LjfTaskEnum.completed;
        } catch (Throwable e) {
            throw new LjfException(this.taskId+ " destroy error:" +e.getMessage());
        }
    }


}
